from django.db import models
from django import forms
from django.shortcuts import Http404
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify

from apps.course.models import CourseForm
from tags.templatetags.sanitize import sanitize

import logging

logger = logging.getLogger('pet.apps.help.models')

# Create your models here.
class FAQ(models.Model):
    category = models.TextField(help_text="A comma-separated list of categories with subcategories separated by dots. Example: activities.content, activities.files.uploads")
    course = models.CharField(max_length=512,blank=True,null=True)
    question_id = models.IntegerField(blank=True, null=True)
    question_link = models.SlugField()
    question = models.CharField(max_length=255)
    quick_answer = models.TextField(blank=True, null=True)
    answer = models.TextField()
    advanced_answer = models.TextField(blank=True, null=True)
    for_admin = models.BooleanField(default=False, help_text = """If True,
            this FAQ appears only to Instructors, Assistants, and Superusers""")
    needs_rendering = models.BooleanField(default=True, help_text = """Set this to True
            if any of Django's templating code is used in this FAQ""")
    def save(self, *args, **kwargs):
        if not self.question_id:
            self.question_id = FAQ.objects.count()
        self.category = sanitize(self.category)
        self.question = sanitize(self.question)
        self.answer = sanitize(self.answer)
        self.question_link = slugify(self.question_link)
        super(FAQ,self).save(*args, **kwargs)
    @staticmethod
    def find(course=None, category=None, question_link=None, include_admin=False):
        logger.find_fxn('course %s, category %s, question_link %s, include_admin %s', course, category, question_link, include_admin)
        Objects = FAQ.objects.all()
        if category: Objects = Objects.filter(category__icontains=category)
        if question_link: Objects = Objects.filter(question_link__iexact=question_link)
        if course: Objects = Objects.filter(models.Q(course__contains=course)|models.Q(course=''))
        if not include_admin and not question_link: Objects = Objects.filter(for_admin=False)
        Objects = Objects.order_by('for_admin','category','question_id')
        if Objects:
            if len(Objects) == 1 and question_link: return Objects[0]
            return Objects
        return None
    @staticmethod
    def find_or_404(course=None, category=None, question_link=None, include_admin=False):
        Results = FAQ.find(course,category,question_link,include_admin)
        if not Results:
            if logger: logger.error('FAQs not found for course %s, category %s, question_link %s, include_admin %s',course,category,question_link,include_admin)
            raise Http404
        return Results

class FAQForm(CourseForm):
    def __init__(self, *args, **kwargs):
        kwargs['allow_none'] = True
        super(FAQForm,self).__init__(*args,**kwargs)
    class Meta:
        model = FAQ
        widgets = {
            'category': forms.TextInput(attrs={'size':100})
        }